import json
import time
import logging
import datetime
import pandas as pd

import QUANTAXIS as QA
from QAStrategy.QAStrategy.qastockbase import QAStrategyStockBase
from QAPUBSUB.QAPUBSUB.producer import publisher, publisher_routing
from QAPUBSUB.QAPUBSUB.consumer import subscriber
from QATrader.QATRADER.trader import QA_TRADER
from QIFIAccount.QIFIAccount.QARealtimeStockSim import QIFI_StockSIM_Account
from QAStrategy.QAStrategy.mc.muti_freq_strategy import MutiFreqStrategy


def main():
    # account
    username = 'MACD_MUTI_FREQ_SIM'
    password = '123456'

    # codes
    codes = ['510050', '510300']

    # frequency
    frequences = [
                  # QA.FREQUENCE.FIVE_MIN,
                  # QA.FREQUENCE.FIFTEEN_MIN,
                  # QA.FREQUENCE.THIRTY_MIN,
                  # QA.FREQUENCE.SIXTY_MIN,
                  QA.FREQUENCE.DAY,
                  # QA.FREQUENCE.WEEK,
                  # QA.FREQUENCE.MONTH,
                  # QA.FREQUENCE.YEAR,
                  QA.FREQUENCE.ONE_MIN  # 多周期策略必须包含1min，触发on_bar
                  ]

    # subscribe codes
    print('start subscribe codes')
    for code in codes:
        publisher_routing(exchange='QARealtime_Market', routing_key='stock').pub(
            json.dumps({
                'topic': 'subscribe',
                'code': code
            }), routing_key='stock'
        )
        print('Subscribe code %s' % code)
        time.sleep(1)

    # strategy
    print('start execute strategy')
    today = datetime.date.today()
    last_year = datetime.date.today() + datetime.timedelta(days=-365)
    last_week = datetime.date.today() + datetime.timedelta(days=-7)
    last_month = datetime.date.today() + datetime.timedelta(days=-30)

    start = last_year.strftime('%Y-%m-%d')
    end = today.strftime('%Y-%m-%d')
    strategy = MutiFreqStrategy(username=username, password=password, code=codes,
                                   market=QA.MARKET_TYPE.INDEX_CN, start=start, end=end, show_trade=True,
                                   min_trade_money=3000, once_trade_money=10000,
                                   frequences=frequences, strategy_id=username, init_cash=1e5)
    strategy.run_sim()


if __name__ == "__main__":
    # try:
    #     from QUANTAXIS_RealtimeCollector.QARealtimeCollector.utils.logconf import update_log_file_config
    #     logfile = 'stock.sim.log'
    #     logging.config.dictConfig(update_log_file_config(logfile))
    # except Exception as e:
    #     print(e.__str__())
    main()